package com.cskaoyan.controller;

import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.vo.AdminStorageCreateVO;
import com.cskaoyan.service.AdminStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @author zhuqiushi
 * @since 2022/09/06 21:51
 */
@RestController
@RequestMapping("admin/storage")
public class AdminStorageController {
    @Autowired
    AdminStorageService adminStorageService;
    /*
     * /admin/storage/create
     * post
     * */
    //获取yml中的静态资源路径
    @Value("${spring.web.resources.static-locations}")
    String staticLocations;

    @RequestMapping("create")
    public BaseRespVo<AdminStorageCreateVO> create(MultipartFile file) throws IOException {
        //在此对文件进行接收，存到本地
        String name = file.getOriginalFilename();
        String contentType = file.getContentType();
        long size = file.getSize();
        AdminStorageCreateVO adminStorageCreateVO = new AdminStorageCreateVO();
        // adminStorageCreateVO.setId();
        //利用uuid生成一个key
        String[] uuids = UUID.randomUUID().toString().split("-");
        String uuid = uuids[0] + uuids[1];
        String key = uuid + "-" + name;
        adminStorageCreateVO.setKey(key);
        adminStorageCreateVO.setName(name);
        adminStorageCreateVO.setSize((int) size);
        adminStorageCreateVO.setType(contentType);
        adminStorageCreateVO.setUrl("http://localhost:8083/wx/storage/fetch/" + key);
        //调用service层将其插入
        int result = adminStorageService.create(adminStorageCreateVO);
        //将其存储到本地
        File receiveFile = new File(staticLocations.substring(5), key);
        //检查是否有该目录
        if (!receiveFile.getParentFile().exists()) {
            //没有的话创建
            receiveFile.getParentFile().mkdirs();
        }
        file.transferTo(receiveFile);
        BaseRespVo ok = BaseRespVo.ok(adminStorageCreateVO);
        if (result == 0) {
            ok.setErrmsg("成功");
            ok.setErrno(0);
        } else {
            ok.setErrmsg("失败");
            ok.setErrno(10000);
        }
        return ok;
    }
}
